package com.atguigu.flow.utils;

import com.atguigu.flow.entity.vo.Module_Field;
import com.atguigu.flow.mapper.SqlMapper;
import org.apache.logging.log4j.util.Strings;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Component
public
class GetFlowModule_field_util {
    @Autowired
    SqlMapper sqlMapper;

    public
    Boolean getflowcondition(String str, String recordid, String modulename) throws DocumentException {
        str = str.toUpperCase();
        Boolean returnstr = null;
        String regex = "Self.QueryRecordValue\\('(.*?)'".toUpperCase();
//        System.out.println(regex);

        String sql = "";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(str);
        String maintablename = "";
        String subtablename = "";

//        recordid = "4E56FBF4-F0B9-422E-A129-C0FB130B184B";
        Map<String, Object> mapList = new HashMap<>();
        List<String> fieldlist = new ArrayList<String>();
        List<Module_Field> module_fieldList = Workflow.module_arraylist;

        //Workflow.getmodle_fieldlist(modulename);
        while (m.find()) {
            String name = m.group(1);
            if (fieldlist.indexOf(name) >= 0) continue;
            else
                fieldlist.add(name);

            System.out.println("name-" + name);
            List<Module_Field> module_fieldList_temp = new ArrayList<Module_Field>();
            System.out.println(module_fieldList_temp);
            module_fieldList_temp = module_fieldList.stream().filter(user -> name.equals(user.getName())).collect(Collectors.toList());

            System.out.println(module_fieldList_temp);
            if (module_fieldList_temp.size() > 0) {


                Module_Field module_field = module_fieldList_temp.get(0);
                String fieldname = module_field.getFieldname();
//                str = str.replace("self.QueryRecordValue('".toUpperCase() + name + "')", fieldname);
                if (str.contains("self.QueryRecordValue('".toUpperCase() + name + "')<>"))
                    str = str.replace("self.QueryRecordValue('".toUpperCase() + name + "')<>", "!" + fieldname + "=");
                else
                    str = str.replace("self.QueryRecordValue('".toUpperCase() + name + "')", fieldname);
                if (!module_field.getIstable()) {
                    if (StringUtils.isEmpty(maintablename))
                        maintablename = module_field.getTablename();
                } else {
                    if (StringUtils.isEmpty(subtablename))

                        subtablename = module_field.getTablename();
                }

                sql = sql + module_field.getTablename() + "." + fieldname + " as " + fieldname + ",";

            }

        }
        System.out.println(str);
        //System.exit(0);
        if (sql.length() > 0) {
            sql = sql.substring(0, sql.length() - 1);
            System.out.println(sql);
            sql = " select top 1 " + sql + " from " + maintablename;
            if (!StringUtils.isEmpty(subtablename))
                sql = sql + " inner join " + subtablename + " on " + maintablename + ".recordid=" + subtablename + ".parentid";
            Map<String, Object> params = new HashMap<>();

            params.clear();
            params.put("sql", sql + " where recordid=#{recordid}");
            params.put("recordid", recordid);

            List<Map<String, Object>> ans = sqlMapper.sqltest(params);
            if (ans.size() > 0) {
                mapList = ans.get(0);
                Set keyset = mapList.keySet();
                for (Object key : keyset) {
                    System.out.println(key + "-" + mapList.get(key));

                }
            }

        }
        if (mapList.size() > 0) {


            //System.exit(0);
            //System.out.println(str);
            //(IStrToFloat

            regex = "IStrToFloat\\((.*?)\\)".toUpperCase();
            p = Pattern.compile(regex);
            m = p.matcher(str);
            while (m.find()) {
                String str1 = m.group(1);
                str = str.replace("IStrToFloat(".toUpperCase() + str1 + ")", str1);
            }


            regex = "pos(.*?)0".toUpperCase();
            p = Pattern.compile(regex);
            m = p.matcher(str);
            while (m.find()) {
                String str1 = m.group(1);
                String str2 = str1.replace("(", "");
                str2 = str2.replace(")", "");
                str2 = str2.replace(">", "");
                str2 = str2.replace("<", "");
                str2 = str2.replace("=", "");

                String[] arraystr = str2.split("[,]");
                if (str1.contains(">"))
                    str2 = (arraystr[1] + ".contains(" + arraystr[0] + ")");
                else
                    str2 = ("!" + arraystr[1] + ".contains(" + arraystr[0] + ")");
                System.out.println(str2);
                //System.out.println("pos("+str1+")");

                str = str.replace("pos".toUpperCase() + str1 + "0", str2);
                //System.out.println(str);

            }
            regex = "'(.*?)'";
            p = Pattern.compile(regex);
            m = p.matcher(str);
            while (m.find()) {
                String str1 = m.group(1);
                str = str.replace("='" + str1 + "'", ".equals(\"" + str1 + "\")");
            }
            str = str.replaceAll("or".toUpperCase(), "||");
            str = str.replaceAll("and".toUpperCase(), "&&");
            str = str.replaceAll("=", "==");
            str = str.replaceAll("'", "\"");
            str = str.replace("<==", "<=");
            str = str.replace(">==", ">=");
            System.out.println(str);
//            System.exit(0);
            ScriptEngineManager manager = new ScriptEngineManager();
            ScriptEngine engine = manager.getEngineByName("js");
            Set keyset = mapList.keySet();
            for (Object key : keyset) {
                System.out.println(key + "-" + mapList.get(key));
                engine.put(String.valueOf(key), mapList.get(key));


            }
//            engine.put("htxz", "库存采购");
//            engine.put("bm", "业务部\\事业八部\\公司三十二部\\A32");
            //engine.put("c",true);
            Object result = null;
            try {
                result = engine.eval(str);
            } catch (ScriptException e) {
                e.printStackTrace();
            }
            System.out.println("结果类型:" + result.getClass().getName() + ",计算结果:" + result);
            if ((Boolean) result == true) returnstr = true;
            else returnstr = false;

        }
        return returnstr;
    }

    public
    String getflowspname(String str, String recordid, String modulename, Boolean... userid) throws DocumentException {
        String returnstr = "";
        returnstr = str;
        String maintablename = "";
        String subtablename = "";
        String sql = "";
        str = str.toUpperCase();
        List<String> names = new ArrayList<>();
        if (str.contains("self.QueryRecordValue".toUpperCase())) {
            String regex = "self.QueryRecordValue\\('(.*?)'".toUpperCase();

            Pattern p = Pattern.compile(regex);
            Matcher m = p.matcher(str);
            while (m.find()) {
                names.add(m.group(1));

            }
        } else
            names.add(str);

//        recordid = "4E56FBF4-F0B9-422E-A129-C0FB130B184B";
        Map<String, Object> mapList = new HashMap<>();
        List<Module_Field> module_fieldList = Workflow.module_arraylist; //Workflow.getmodle_fieldlist(modulename);
        for (String name : names) {

            System.out.println(name);
            List<Module_Field> module_fieldList_temp = new ArrayList<Module_Field>();
            module_fieldList_temp = module_fieldList.stream().filter(user -> name.equals(user.getName())).collect(Collectors.toList());

            System.out.println(module_fieldList_temp);
            if (module_fieldList_temp.size() > 0) {


                Module_Field module_field = module_fieldList_temp.get(0);
                String fieldname = module_field.getFieldname();
                str = str.replace("self.QueryRecordValue('".toUpperCase() + name + "')", fieldname);
                if (!module_field.getIstable()) {
                    if (StringUtils.isEmpty(maintablename))
                        maintablename = module_field.getTablename();
                } else {
                    if (StringUtils.isEmpty(subtablename))

                        subtablename = module_field.getTablename();
                }

                sql = sql + module_field.getTablename() + "." + fieldname + " as " + fieldname + ",";

            }

        }
        //System.out.println(str);
        //System.exit(0);


        if (sql.length() > 0) {
            sql = sql.substring(0, sql.length() - 1);
            System.out.println(sql);
            sql = " select top 1 " + sql + " from " + maintablename;
            if (!StringUtils.isEmpty(subtablename))
                sql = sql + " inner join " + subtablename + " on " + maintablename + ".recordid=" + subtablename + ".parentid";
            Map<String, Object> params = new HashMap<>();

            params.clear();
            params.put("sql", sql + " where recordid=#{recordid}");
            params.put("recordid", recordid);

            List<Map<String, Object>> ans = sqlMapper.sqltest(params);
            returnstr = null;
            if (!StringUtils.isEmpty(ans) && ans.size() > 0) {
                System.out.println("01");
                mapList = ans.get(0);
                if (!StringUtils.isEmpty(mapList)) {
                    Set keyset = mapList.keySet();
                    for (Object key : keyset) {
                        //System.out.println(key + "-" + mapList.get(key));
                        if (!StringUtils.isEmpty(key) && !StringUtils.isEmpty(mapList.get(key)))
                            returnstr = String.valueOf(mapList.get(key));

                    }
                }
            }

        }

        if (!StringUtils.isEmpty(userid) && userid.length > 0) {
            if (userid[0]) {
                Map<String, Object> params = new HashMap<>();

                returnstr = returnstr.replace("'", "");
                System.out.println("old:" + returnstr);
                params.clear();
                params.put("sql", "select dbo.getuserid(#{username}) as userid");
                params.put("username", returnstr);

                returnstr = sqlMapper.dic_type(params);
                System.out.println("userid:" + returnstr);
            }
        }
        System.out.println("returnstr" + returnstr);
        return returnstr;
    }

    public
    String OnCalcExecutorRange(String modulename, String recordid, String unitname) throws DocumentException {
        String sql = "";
        String bmjl = "";
        if (modulename.equals("赊销额度申请")) {
            if (unitname.equals("jlsp")) {
                sql = "SELECT EmployeeCHNname, Manager, dbo.getuserid(bmjl)bmjl, zwlb FROM Dic_Employee WHERE EmployeeCHNname = #{EmployeeCHNname}";

                Map<String, Object> params = new HashMap<>();

                params.clear();
                params.put("sql", sql);
                params.put("EmployeeCHNname", getflowspname("申请人", recordid, modulename));

                List<Map<String, Object>> ans = sqlMapper.sqltest(params);
                if (ans.size() > 0) {
                    Map<String, Object> mapList = ans.get(0);
//               String sZW = mapList.get("zwlb").toString();
                    bmjl = mapList.get("bmjl").toString();
                } else bmjl = "未找到事业部经理";

                //return bmjl;


            }
        }
        if (modulename.equals("工厂资料")) {
            if (unitname.equals("bmjlsp")) {
                sql = "SELECT EmployeeCHNname, dbo.getuserid(Manager)Manager, dbo.getuserid(bmjl)bmjl, zwlb FROM Dic_Employee WHERE EmployeeCHNname = #{EmployeeCHNname}";

                Map<String, Object> params = new HashMap<>();

                params.clear();
                params.put("sql", sql);
                params.put("EmployeeCHNname", getflowspname("最后修改人", recordid, modulename));

                List<Map<String, Object>> ans = sqlMapper.sqltest(params);
                if (ans.size() > 0) {
                    Map<String, Object> mapList = ans.get(0);
//               String sZW = mapList.get("zwlb").toString();
                    bmjl = mapList.get("bmjl").toString();
                } else bmjl = "";
            }

        }


        if (modulename.equals("客户资料")) {
            if (unitname.equals("jlsp") || unitname.equals("A32_sybjl")) {
                sql = "SELECT EmployeeCHNname, dbo.getuserid(Manager)Manager, dbo.getuserid(bmjl)bmjl,  zwlb FROM Dic_Employee WHERE EmployeeCHNname = #{EmployeeCHNname}";

                Map<String, Object> params = new HashMap<>();

                params.clear();
                params.put("sql", sql);
                params.put("EmployeeCHNname", getflowspname("操作员", recordid, modulename));

                List<Map<String, Object>> ans = sqlMapper.sqltest(params);
                if (ans.size() > 0) {
                    Map<String, Object> mapList = ans.get(0);
//               String sZW = mapList.get("zwlb").toString();
                    bmjl = mapList.get("bmjl").toString();
                } else bmjl = sqlMapper.get_userid("刘金鹏");
            }
            if (unitname.equals("sjldsp")) {
                sql = "SELECT dbo.getuserid(EmployeeCHNname)EmployeeCHNname, dbo.getuserid(Manager)Manager, dbo.getuserid(bmjl)bmjl,  zwlb FROM Dic_Employee WHERE EmployeeCHNname = #{EmployeeCHNname}";

                Map<String, Object> params = new HashMap<>();

                params.clear();
                params.put("sql", sql);
                params.put("EmployeeCHNname", getflowspname("操作员", recordid, modulename));

                List<Map<String, Object>> ans = sqlMapper.sqltest(params);
                if (ans.size() > 0) {
                    Map<String, Object> mapList = ans.get(0);
                    String sZW = mapList.get("zwlb").toString();
                    if (sZW.equals("跟单员"))
                        bmjl = mapList.get("Manager").toString();
                    else if (sZW.equals("业务主管"))
                        bmjl = mapList.get("bmjl").toString();
                    else if (sZW.equals("事业部经理"))
                        bmjl = mapList.get("EmployeeCHNname").toString();


                } else bmjl = sqlMapper.get_userid("刘金鹏");
            }
        }
        //索赔管理
        if (modulename.equals("索赔管理")) {
            if (unitname.equals("jlsp") || unitname.equals("MangerApproval")) {


                sql = "SELECT EmployeeCHNname, dbo.getuserid(Manager)Manager, dbo.getuserid(bmjl)bmjl,  zwlb FROM Dic_Employee WHERE EmployeeCHNname = #{EmployeeCHNname}";

                Map<String, Object> params = new HashMap<>();

                params.clear();
                params.put("sql", sql);
                params.put("EmployeeCHNname", getflowspname("跟单员", recordid, modulename));

                List<Map<String, Object>> ans = sqlMapper.sqltest(params);
                if (ans.size() > 0) {
                    Map<String, Object> mapList = ans.get(0);
//               String sZW = mapList.get("zwlb").toString();
                    if (unitname.equals("jlsp"))
                        bmjl = mapList.get("bmjl").toString();
                    else
                        bmjl = mapList.get("Manager").toString();
                } else bmjl = sqlMapper.get_userid("刘金鹏");
            }



        }
        return bmjl;
    }


    public Boolean OnCalcCondition(String modulename,String recordid,String unitname) throws DocumentException {
        String sql = "";
        String bmjl = "";
        String Manager="";
        Boolean returnstr=false;

        if (modulename.equals("索赔管理")) {
            if (unitname.equals("bstyr")) {

                sql = "SELECT bmjl,Manager FROM Dic_Employee WHERE EmployeeCHNname = #{EmployeeCHNname}";

                Map<String, Object> params = new HashMap<>();

                params.clear();
                params.put("sql", sql);
                params.put("EmployeeCHNname", getflowspname("跟单员", recordid, modulename));
                List<Map<String, Object>> ans = sqlMapper.sqltest(params);
                if (ans.size() > 0) {
                    Map<String, Object> mapList = ans.get(0);
                    bmjl = mapList.get("bmjl").toString();
                    Manager = mapList.get("Manager").toString();
                    if (!bmjl.equals(Manager)) returnstr = true;
                }
            }
            if (unitname.equals("jepd1")) {
                String str=getflowspname("Self.QueryRecordValue('索赔金额')", recordid, modulename);
                Double last_zxed=Double.parseDouble(str);
                String currency=getflowspname("Self.QueryRecordValue('外销币种')", recordid, modulename);
                System.out.println(last_zxed);
                System.out.println(currency);
                Map<String, Object> params = new HashMap<>();
                Double rate=1.00;
                params.clear();
                params.put("sql", "select rate from  Dic_Currency where CurrencyCode=#{CurrencyCode} ");
                params.put("CurrencyCode", "USD");
                 str=sqlMapper.dic_type(params);
                if (!StringUtils.isEmpty(str)&&!str.equals(""))
                    rate=Double.parseDouble(str);
                if (currency.equals("CNY")){
                    last_zxed=last_zxed/rate;


                }

                if ((last_zxed >= 10000))
                    returnstr=true;
                System.out.println(returnstr);
            }

        }
        if (modulename.equals("赊销额度申请")) {
            if (unitname.equals("bstyr")) {

                sql = "SELECT bmjl FROM Dic_Employee WHERE EmployeeCHNname = #{EmployeeCHNname}";

                Map<String, Object> params = new HashMap<>();

                params.clear();
                params.put("sql", sql);
                params.put("EmployeeCHNname", getflowspname("操作员", recordid, modulename));
                List<Map<String, Object>> ans = sqlMapper.sqltest(params);
                if (ans.size() > 0) {
                    Map<String, Object> mapList = ans.get(0);
                    bmjl = mapList.get("bmjl").toString();
                    if (!bmjl.equals("蔡辉")) returnstr = true;
                }
            }
            if (unitname.equals("zjhzed(100)")) {
                String str=getflowspname("Self.QueryRecordValue('追加后总额度')", recordid, modulename);
                Float last_zxed=Float.parseFloat(str);
                String nbhs=getflowspname("Self.QueryRecordValue('内部核算')", recordid, modulename);
                System.out.println(last_zxed);
                System.out.println(nbhs);
                if ((last_zxed >= 1000000)&& (nbhs.contains("A32")))
                    returnstr=true;
                System.out.println(returnstr);


            }
        }

        if (modulename.equals("客户资料")) {

            if (unitname.equals("sffd")) {
                String jhfs=getflowspname("Self.QueryRecordValue('结汇方式')", recordid, modulename);
                String yjbl=getflowspname("Self.QueryRecordValue('佣金比率')", recordid, modulename);
                String qtfy=getflowspname("Self.QueryRecordValue('其他费用')", recordid, modulename);
                String xbed=getflowspname("Self.QueryRecordValue('信保额度')", recordid, modulename);
                String sxed=getflowspname("Self.QueryRecordValue('赊销额度')", recordid, modulename);
                String tcbl=getflowspname("Self.QueryRecordValue('提成比率')", recordid, modulename);
                String bm=getflowspname("Self.QueryRecordValue('部门')", recordid, modulename);
                if (jhfs.contains("T/T Before Shipment") || jhfs.contains("T/T AT SIGHT") ||
                        jhfs.contains("deposit")||jhfs.equals("L/C AT SIGHT;T/T AT SIGHT"))
                    returnstr = true;
                if ( jhfs.contains("D/A")|| (jhfs.contains("T/T") && (Float.parseFloat(sxed)-Float.parseFloat(xbed)>30000))
                        || Float.parseFloat(yjbl)>0  || Float.parseFloat(qtfy)>0 || Float.parseFloat(tcbl)>0)
                    returnstr = true;
                if (bm.equals("国内事业部"))  returnstr=true;

             }
            if (unitname.equals("bmpd")) {
                String sBM=getflowspname("Self.QueryRecordValue('部门')", recordid, modulename);
                if (!sBM.equals("格联")) returnstr=true;


            }

            if (unitname.equals("sftb")) {
                String jhfs=getflowspname("Self.QueryRecordValue('结汇方式')", recordid, modulename);
                String yjbl=getflowspname("Self.QueryRecordValue('佣金比率')", recordid, modulename);
                String qtfy=getflowspname("Self.QueryRecordValue('其他费用')", recordid, modulename);
                String xbed=getflowspname("Self.QueryRecordValue('信保额度')", recordid, modulename);
                String sxed=getflowspname("Self.QueryRecordValue('赊销额度')", recordid, modulename);
                String tcbl=getflowspname("Self.QueryRecordValue('提成比率')", recordid, modulename);
                String bm=getflowspname("Self.QueryRecordValue('部门')", recordid, modulename);
                if (jhfs.contains("T/T Before Shipment") || jhfs.contains("T/T AT SIGHT") ||
                        jhfs.contains("deposit")||jhfs.equals("L/C AT SIGHT;T/T AT SIGHT"))
                    returnstr = true;
                if ( jhfs.contains("D/A")|| (jhfs.contains("T/T") && (Float.parseFloat(sxed)-Float.parseFloat(xbed)>100000))
                       )
                    returnstr = true;


            }
            if (unitname.equals("bstyr")||unitname.equals("bstyr_zjl")||unitname.equals("not_same_sybjl")||unitname.equals("bstyra")) {

                sql = "SELECT bmjl,zjl,Manager FROM Dic_Employee WHERE EmployeeCHNname = #{EmployeeCHNname}";

                Map<String, Object> params = new HashMap<>();

                params.clear();
                params.put("sql", sql);
                params.put("EmployeeCHNname", getflowspname("操作员", recordid, modulename));
                List<Map<String, Object>> ans = sqlMapper.sqltest(params);
                if (ans.size() > 0) {
                    Map<String, Object> mapList = ans.get(0);

                    Manager = mapList.get("Manager").toString();
                    bmjl = mapList.get("bmjl").toString();
                    String zjl=mapList.get("zjl").toString();
                    if (unitname.equals("bstyr")||unitname.equals("bstyr_zjl")){
                    if (!bmjl.equals(zjl)) returnstr = true;}
                    else if (unitname.equals("not_same_sybjl")){
                        if (!bmjl.equals(Manager)) returnstr = true;
                    }
                    else if (unitname.equals("bstyra")){
                        if (!bmjl.equals("蔡辉")) returnstr = true;
                    }

                }
            }

            }

        if (modulename.equals("工厂资料")) {
            if (unitname.equals("fkfspd")) {
                String qxgm=getflowspname("Self.QueryRecordValue('企业规模')", recordid, modulename);
                String fkbh=getflowspname("Self.QueryRecordValue('付款编号')", recordid, modulename);
                String hzzj=getflowspname("Self.QueryRecordValue('战略工厂')", recordid, modulename);
                String creditdesc=getflowspname("Self.QueryRecordValue('企业信用信息公示系统情况')", recordid, modulename);
                String cgbz=getflowspname("Self.QueryRecordValue('采购币种')", recordid, modulename);
                String bm=getflowspname("Self.QueryRecordValue('部门')", recordid, modulename);


                String jckdm=getflowspname("Self.QueryRecordValue('进出口企业代码')", recordid, modulename);
                 //jckdm=getflowspname("Self.QueryRecordValue('进出口企业代码')", recordid, modulename);


                //if (qxgm.equals("小型")||qxgm.equals("微型"))  returnstr=true;
                if (fkbh.equals("02")||fkbh.equals("09")||fkbh.equals("04"))  returnstr=true;
                if (hzzj.equals("战略工厂"))  returnstr=true;
                if (creditdesc.equals("有不良记录"))  returnstr=true;
                if (cgbz.equals("USD")&&(StringUtils.isEmpty(jckdm)||jckdm.equals("")))  returnstr=true;
                if (bm.equals("国内事业部"))  returnstr=true;

//                AResult := False;
//                if (Self.QueryRecordValue('企业规模') = '小型') or (Self.QueryRecordValue('企业规模') = '微型') then
//                AResult := True;
//                if (Self.QueryRecordValue('付款编号') = '02') or (Self.QueryRecordValue('付款编号') = '09') or (Self.QueryRecordValue('付款编号') = '04') then
//                AResult := True;
//                if Self.QueryRecordValue('合作质级') = '战略工厂' then
//                AResult := True;
//                if Self.QueryRecordValue('企业信用信息公示系统情况') = '有不良记录' then
//                AResult := True;
//                if (Self.QueryRecordValue('采购币种') = 'USD') and (trim(Self.QueryRecordValue('进出口企业代码')) = '') then
//                AResult := True;
//                if pos('国内事业部',Self.QueryRecordValue('部门')) > 0 then
//                AResult := True;
            }

            }

        return returnstr;
    }


    public Integer DoAfterFinish(String modulename,String recordid){
        String sql="";
        Integer count=0;
        if (modulename.equals("工厂资料")) {
            Map<String, Object> params = new HashMap<>();
            params.clear();
            params.put("sql", "update Suppliers Set spzt=#{spzt}, Archived = 1 Where RecordID=#{RecordID}");
            params.put("RecordID", recordid);
            params.put("spzt", "已审批");

            count = sqlMapper.sql_update(params);
            System.out.println(count);

            params.clear();
            params.put("sql", "Update Suppliers Set  xzcs=(case when xzcs=-1 then 3 else  xzcs+3 end) Where RecordID=#{RecordID}");
            params.put("RecordID", recordid);
            sqlMapper.sql_update(params);

            params.clear();
            params.put("sql", "Update Suppliers Set sycs=xzcs-yycs Where  RecordID=#{RecordID}");
            params.put("RecordID", recordid);
            sqlMapper.sql_update(params);


        }
        if (modulename.equals("客户资料")) {
            Map<String, Object> params = new HashMap<>();
            params.clear();
            params.put("sql", "Update Customers Set  spzt=#{spzt}, Archived = 1 Where RecordID=#{RecordID}");
            params.put("RecordID", recordid);
            params.put("spzt", "已审批");
            count = sqlMapper.sql_update(params);
            System.out.println(count);

        }

        return count;
    }

    public String sybjl(String modulename,String unitname,String username){
        String sql="";
        String bmjl="";
        if (modulename.equals("赊销额度申请")){
            if (unitname.equals("jlsp")){
                sql="SELECT EmployeeCHNname, Manager, bmjl, zwlb FROM Dic_Employee WHERE EmployeeCHNname = #{EmployeeCHNname}";

                Map<String, Object> params = new HashMap<>();

                params.clear();
                params.put("sql", sql);
                params.put("EmployeeCHNname", username);

                List<Map<String, Object>> ans = sqlMapper.sqltest(params);
                if (ans.size()>0){
                    Map<String, Object> mapList = ans.get(0);
//               String sZW = mapList.get("zwlb").toString();
                    bmjl=mapList.get("bmjl").toString();}
                else bmjl="未找到事业部经理";

                //return bmjl;


            }
        }
        return bmjl;
    }

    public boolean  changeusr(Element rootElt,String olduser,String newuser) throws DocumentException {
        List<Element> ActivityNodeList = rootElt.selectNodes("/data/TcxFlow/Objects/TcxFlowActivityUnit");
        Boolean ischange=false;
        for (int i = 0; i <= ActivityNodeList.size() - 1; i++) {
            Element lNodeItem = ActivityNodeList.get(i);
            if (!StringUtils.isEmpty(lNodeItem.selectSingleNode("RuntimeProperties"))) {
                List<Element> itemlist = lNodeItem.selectNodes("RuntimeProperties/Tasks/Item");
                for (int j = 0; j <= itemlist.size() - 1; j++) {
                    String sender=itemlist.get(j).selectSingleNode("Executor").getStringValue();
                    if (sender.equals(olduser)){
                        itemlist.get(j).selectSingleNode("Executor").setText(newuser);
                        ischange=true;
                    }


                }

            }
        }
        return  ischange;

    }

    public  Boolean ative_elemnt(String recordid,String modulename,String content,Element rootElt,Boolean condition, Map<String, Object> params,Date spectime) throws DocumentException {
//         = new HashMap<>();
        List<Element> ActivityNodeList = rootElt.selectNodes("/data/TcxFlow/Objects/TcxFlowActivityUnit");
        if (condition)
        params.put("State",2);
        else
            params.put("State",3);
        if (condition)    params.put("condition",condition);
        boolean isfind=false;
       for (int i = 0; i <= ActivityNodeList.size() - 1; i++) {
           Element lNodeItem = ActivityNodeList.get(i);
           if (!StringUtils.isEmpty(lNodeItem.selectSingleNode("RuntimeProperties"))) {
               if (!StringUtils.isEmpty(lNodeItem.selectSingleNode("RuntimeProperties/State"))){
                  if (lNodeItem.selectSingleNode("RuntimeProperties/State").getStringValue().equals("rsAcitve"))
                  {
                      String Caption=lNodeItem.selectSingleNode("Caption").getStringValue();
                      //params.put("State",2);
                      params.put("LastFlowActivity",Caption);

                      Integer level=Integer.valueOf(lNodeItem.selectSingleNode("RuntimeProperties/Level").getStringValue());
                      String unitname= lNodeItem.selectSingleNode("NextUnit").getStringValue();


                      List<Element> itemlist = lNodeItem.selectNodes("RuntimeProperties/Tasks/Item");
                      for (int j = 0; j <= itemlist.size() - 1; j++) {

                          if (StringUtils.isEmpty(itemlist.get(j).selectSingleNode("State"))){
                              Element itemnode = itemlist.get(j).addElement("State");
                              if (condition)
                              itemnode.setText("tsPassed");
                              else
                                  itemnode.setText("tsRejected");
                              if (!StringUtils.isEmpty(content)){
                                  itemnode=itemlist.get(j).addElement("Content");
                                  itemnode.setText(content);
                              }
                              itemnode=itemlist.get(j).addElement("FinishTime");
                              //itemnode.setText(DateUtil.formatDate_spec(new Date(),"yyyy-MM-dd")+"T"+DateUtil.formatDate_spec(new Date(),"HH:mm:ss.SSS"));
                              //String FinishTime=DateUtil.formatDate_spec(new Date(),"yyyy-MM-dd HH:mm:ss");

                              itemnode.setText(DateUtil.formatDate_spec(spectime,"yyyy-MM-dd")+"T"+DateUtil.formatDate_spec(spectime,"HH:mm:ss.SSS"));
                              String FinishTime=DateUtil.formatDate_spec(spectime,"yyyy-MM-dd HH:mm:ss");
                              params.put("FinishTime",FinishTime);


                              lNodeItem.selectSingleNode("RuntimeProperties/State").setText("rsFlowOut");
                              String sender=itemlist.get(j).selectSingleNode("Sender").getStringValue();
                              String lastunitname=lNodeItem.selectSingleNode("Name").getStringValue();
                              String subject=itemlist.get(j).selectSingleNode("Subject").getStringValue();
                              subject=subject.replace(Caption,"");
                              params.put("subject",subject);
                              System.out.println("已找到当前活动节点"+lastunitname
                                      +"/下一节点"+unitname+"/level"+String.valueOf(level++));
                              if (lastunitname.equals("BackApproval")) condition=null;
                              find_flow_nextbranch(recordid, modulename,content, rootElt, lastunitname,unitname, level++, condition,sender,params,spectime);

                              isfind=true;

                              return isfind;
                              //break;

                          }
                      }

                      //break;
                      return null;


                  }

               }
           }

           }


        return null;
   };





    public  Boolean find_flow_nextbranch( String recordid,String modulename,String content,Element rootElt, String lastunitname, String unitname,Integer level,Boolean condition,String sender,Map<String, Object> params,Date spectime) throws DocumentException {
        List<Element> ActivityNodeList = rootElt.selectNodes("/data/TcxFlow/Objects/TcxFlowConditionBranchUnit");
        String nextunitname = "";
//        Map<String, Object> params = new HashMap<>();
        boolean isfind=false;
        for (int i = 0; i <= ActivityNodeList.size() - 1; i++) {
            Element lNodeItem = ActivityNodeList.get(i);
            if (lNodeItem.selectSingleNode("Name").getStringValue().equals(unitname)) {
                if (!StringUtils.isEmpty(lNodeItem.selectSingleNode("RuntimeProperties"))) {
                    lNodeItem.selectSingleNode("RuntimeProperties/State").setText("rsFlowOut");
                    lNodeItem.selectSingleNode("RuntimeProperties/Level").setText(String.valueOf(level));
                    lNodeItem.selectSingleNode("RuntimeProperties/FlowFromUnits").setText(unitname);


                } else {
                    Element itemnode = lNodeItem.addElement("RuntimeProperties");
                    Element node2 = itemnode.addElement("State");
                    node2.setText("rsFlowOut");
                    node2 = itemnode.addElement("Level");
                    node2.setText(String.valueOf(level));
                    node2 = itemnode.addElement("FlowFromUnits");
                    node2.setText(lastunitname);


                }
                if (!StringUtils.isEmpty(condition)) {
                    if (condition == true)
                        nextunitname = lNodeItem.selectSingleNode("TrueUnit").getStringValue();
                    else
                        nextunitname = lNodeItem.selectSingleNode("FalseUnit").getStringValue();
                } else {

                    if (!StringUtils.isEmpty(lNodeItem.selectSingleNode("OnCalcCondition/Script")))
                    {
                        System.out.println("执行脚本"+unitname);
                        condition=OnCalcCondition(modulename,recordid,unitname);}
                       else
                    {
                        System.out.println("执行条件判断:/"+unitname);
                    condition = getflowcondition(lNodeItem.selectSingleNode("Condition").getStringValue(), recordid, modulename);}
                    if (condition == true)
                        nextunitname = lNodeItem.selectSingleNode("TrueUnit").getStringValue();
                    else
                        nextunitname = lNodeItem.selectSingleNode("FalseUnit").getStringValue();
                }
                if (!StringUtils.isEmpty(nextunitname)) {
                    System.out.println("已找到当前条件分支"+unitname+"/level:"+String.valueOf(level++)+"下一节点:"+nextunitname);
                    find_flow_nextbranch(recordid, modulename,content, rootElt, unitname,nextunitname, level++, null,sender,params,spectime);
                    isfind=true;
                    return isfind;

                }

            }


        }
        if (!isfind)
            find_flow_nextunit(recordid,modulename,content,rootElt,lastunitname,unitname,level,sender,params,spectime);
        return null;
    }


    public
    Boolean find_flow_nextunit(String recordid,String modulename,String content, Element rootElt, String lastunitname,String unitname,Integer level,String sender,Map<String, Object> params,Date spectime) throws DocumentException {
        List<Element> ActivityNodeList = rootElt.selectNodes("/data/TcxFlow/Objects/TcxFlowActivityUnit");
        String nextunitname = "";
        String Caption="";
        boolean isfind=false;
        for (int i = 0; i <= ActivityNodeList.size() - 1; i++) {
            Element lNodeItem = ActivityNodeList.get(i);
            if (lNodeItem.selectSingleNode("Name").getStringValue().equals(unitname)) {
                Caption=lNodeItem.selectSingleNode("Caption").getStringValue();
                System.out.println("已找到当前审批节点："+unitname+"正在等待审批");
                if (StringUtils.isEmpty(lNodeItem.selectSingleNode("RuntimeProperties"))) {
                    Element itemnode = lNodeItem.addElement("RuntimeProperties");
                    Element node2 = itemnode.addElement("State");
                     node2 = itemnode.addElement("Level");
                    node2 = itemnode.addElement("FlowFromUnits");
                    node2 = itemnode.addElement("Tasks");

                }
                lNodeItem.selectSingleNode("RuntimeProperties/State").setText("rsAcitve");
                lNodeItem.selectSingleNode("RuntimeProperties/Level").setText(String.valueOf(level));
                lNodeItem.selectSingleNode("RuntimeProperties/FlowFromUnits").setText(lastunitname);
                Element itemnode =(Element) lNodeItem.selectSingleNode("RuntimeProperties/Tasks");
                Element node2 = itemnode.addElement("Item");
                Element node3 = node2.addElement("TaskID");
                String taskid=UUID.randomUUID().toString().toUpperCase();
                String subject=Caption+params.get("subject").toString();
                node3.setText(taskid);
                node3 = node2.addElement("Sender");
                node3.setText(sender);
                node3 = node2.addElement("Subject");
                node3.setText(subject);

                node3 = node2.addElement("Executor");
                String executor="";

                    if (!StringUtils.isEmpty(lNodeItem.selectSingleNode("OnCalcExecutorRange/Script"))) {


                        executor = OnCalcExecutorRange(modulename, recordid, unitname);

                    } else


                        if (!StringUtils.isEmpty(lNodeItem.selectSingleNode("ExecuteProperties/ExecutorRange")))
                        executor = getflowspname(lNodeItem.selectSingleNode("ExecuteProperties/ExecutorRange").getStringValue(), recordid, modulename, true);
                        else
                            executor=sender;
                        if (StringUtils.isEmpty(executor)||executor.equals(""))
                            executor=sender;

                node3.setText(executor);


                node3=node2.addElement("ReceiveTime");

                node3.setText(DateUtil.formatDate_spec(spectime,"yyyy-MM-dd")+"T"+DateUtil.formatDate_spec(spectime,"HH:mm:ss.SSS"));
                isfind=true;
                String ReceiveTime=DateUtil.formatDate_spec(spectime,"yyyy-MM-dd HH:mm:ss");
//                Map<String, Object> params = new HashMap<>();

//                params.clear();
                params.put("TaskID",taskid);
                params.put("ReceiveTime",ReceiveTime);
                params.put("Sender",sender);
                params.put("Executor",executor);
                params.put("unitname",unitname);

//                params.put("LastFlowActivity",lastunitname);
                params.put("CurrentFlowActivity",Caption);

                params.put("subject",subject);
                return  true;

            }

            }

            if (!isfind) {
                ActivityNodeList = rootElt.selectNodes("/data/TcxFlow/Objects/TcxFlowFinishUnit");

                for (int i = 0; i <= ActivityNodeList.size() - 1; i++) {
                    Element lNodeItem = ActivityNodeList.get(i);
                    if (lNodeItem.selectSingleNode("Name").getStringValue().equals(unitname)) {
                        Caption = lNodeItem.selectSingleNode("Name").getStringValue();
                        System.out.println("已找到当前结束节点：" + unitname + "正在结束审批");
                        if (StringUtils.isEmpty(lNodeItem.selectSingleNode("RuntimeProperties"))) {
//                            System.out.println("01");
                            Element itemnode = lNodeItem.addElement("RuntimeProperties");
                            Element node2 = itemnode.addElement("State");
                            node2 = itemnode.addElement("Level");
                            node2 = itemnode.addElement("FlowFromUnits");
//                            System.out.println("02");
                        }
                        lNodeItem.selectSingleNode("RuntimeProperties/State").setText("rsFlowOut");
//                        System.out.println("03");
                        lNodeItem.selectSingleNode("RuntimeProperties/Level").setText(String.valueOf(level));
//                        System.out.println("04");
                        lNodeItem.selectSingleNode("RuntimeProperties/FlowFromUnits").setText(lastunitname);
//                        System.out.println("05");
                        params.put("CurrentFlowActivity","已结束");
                        params.put("endflow", true);
                        params.put("unitname", unitname);
                        return true;


                    }

                }
            }

        return null;
    }
}
